<template>
  <div v-html="renderedContent"></div>
</template>

<script>
import katex from 'katex'
import 'katex/dist/katex.min.css'

export default {
  props: {
    content: {
      type: String,
      required: true
    }
  },
  computed: {
    renderedContent() {
      return this.content
          // 行内公式 $...$
          .replace(/\$([^$]+)\$/g, (match, p1) => {
            return katex.renderToString(p1, { throwOnError: false })
          })
          // 块级公式 \\[...\\]
          .replace(/\\\[([^\]]+)\\\]/g, (match, p1) => {
            return `<div>${katex.renderToString(p1, { displayMode: true, throwOnError: false })}</div>`
          })
          // 块级公式 \begin{...}...\end{...}
          .replace(/\\begin\{([a-zA-Z]+)\}([\s\S]+?)\\end\{\1\}/g, (match, environment, content) => {
            return `<div>${katex.renderToString(`\\begin{${environment}}${content}\\end{${environment}}`, { displayMode: true, throwOnError: false })}</div>`
          })
    }
  }
}
</script>
